const express = require('express');
const router = express.Router();
const Employee = require('../models/employee');
const { log } = require('console');

// 添加员工
router.post('/', async (req, res) => {
    try {
        const employeeData = req.body;
        const employeeId = await Employee.addEmployee(employeeData);
        res.status(200).json({ code: 200, employee_id: employeeId });
    } catch (err) {
        res.status(500).json({ code: 500, message: err.message });
    }
});

// 获取所有员工
router.get('/', async (req, res) => {
    const { currentPage, pageSize, searchMsg } = req.query;
    try {
        const employees = await Employee.getAllEmployees(currentPage, pageSize, searchMsg);
        res.status(200).json(employees);
    } catch (err) {
        res.status(500).json({ code: 500, message: err.message });
    }
});

// 根据员工ID获取员工
router.get('/:employee_id', async (req, res) => {
    const { employee_id } = req.params;
    try {
        const employee = await Employee.getEmployeeById(employee_id);
        if (employee) {
            res.status(200).json(employee);
        } else {
            res.status(404).json({ code: 404, message: '员工未找到' });
        }
    } catch (err) {
        res.status(500).json({ code: 500, message: err.message });
    }
});

// 更新员工信息
router.put('/:employee_id', async (req, res) => {
    const { employee_id } = req.params;
    const employeeData = req.body;
    try {
        const updated = await Employee.updateEmployee(Number(employee_id), employeeData);
        if (Number(updated) > 0) {
            res.status(200).json({ code: 200, message: '员工信息更新成功' });
        } else {
            res.status(404).json({ code: 404, message: '员工未找到' });
        }
    } catch (err) {
        res.status(500).json({ code: 500, message: err.message });
    }
});

// 删除员工
router.delete('/:employee_id', async (req, res) => {
    const { employee_id } = req.params;
    try {
        const deleted = await Employee.deleteEmployee(Number(employee_id));
        if (Number(deleted) > 0) {
            res.status(200).json({ code: 200, message: '员工删除成功' });
        } else {
            res.status(404).json({ code: 404, message: '员工未找到' });
        }

    } catch (err) {
        res.status(500).json({ code: 500, message: err.message });
    }
});

module.exports = router;
